package com.succez.server.servlet.config;

import java.io.File;
import java.io.FileInputStream;
import java.util.HashMap;
import java.util.concurrent.ConcurrentHashMap;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import com.succez.server.servlet.Servlet;
import com.succez.server.servlet.ServletContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class XMLConfigReader implements ConfigReader {

    private final static HashMap<String, String> servletInfos;

    private final static HashMap<String, String> servletMappings;

    private final static ConcurrentHashMap<String, Servlet> servletObj;

    private final static ServletContext servletContext;

    private static final Logger logger;

    static {
        servletInfos = new HashMap<String, String>();
        servletMappings = new HashMap<String, String>();
        servletObj = new ConcurrentHashMap<String, Servlet>();
        servletContext = new ServletContext(servletInfos, servletMappings, servletObj);
        logger = LoggerFactory.getLogger(XMLConfigReader.class);
    }

    @Override
    public ServletContext parse(String path) throws Exception {
        File currDirectory = new File(".");
        currDirectory.getCanonicalPath();
        File file = new File(currDirectory.getCanonicalPath(), path);
        if (!file.exists()) {
            logger.error("找不到配置文件", "");
            return null;
        }
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        Document doc = documentBuilder.parse(new FileInputStream(file));
        NodeList servletInfoList = doc.getElementsByTagName("servlet");
        NodeList servletMappingList = doc.getElementsByTagName("servlet-mapping");
        String servletName = "";
        String servletClass = "";
        String urlPattern = "";
        // 填充servletInfos
        for (int i = 0; i < servletInfoList.getLength(); i++) {
            final NodeList childNodes = servletInfoList.item(i).getChildNodes();
            for (int j = 0; j < childNodes.getLength(); j++) {
                final Node item = childNodes.item(j);
                if ("servlet-name".equals(item.getNodeName())) {
                    servletName = item.getFirstChild().getNodeValue();
                } else if ("servlet-class".equals(item.getNodeName())) {
                    servletClass = item.getFirstChild().getNodeValue();
                }
            }
            servletInfos.put(servletName, servletClass);
            servletName = "";
            servletClass = "";
        }
        servletName = "";
        // 填充servletMappings
        for (int i = 0; i < servletMappingList.getLength(); i++) {
            final NodeList childNodes = servletMappingList.item(i).getChildNodes();
            for (int j = 0; j < childNodes.getLength(); j++) {
                final Node item = childNodes.item(j);
                if ("servlet-name".equals(item.getNodeName())) {
                    servletName = item.getFirstChild().getNodeValue();
                } else if ("url-pattern".equals(item.getNodeName())) {
                    urlPattern = item.getFirstChild().getNodeValue();
                }
            }
            servletMappings.put(urlPattern, servletName);
        }
        // 初始化servlet
        initServlet(servletInfos, servletMappings, servletObj);
        return servletContext;
    }

    /**
     * 
     * @param servletinfos    servlet名和类全路径名映射
     * @param servletmappings servlet名和url映射
     * @param servletobj      servlet名和servlet实例映射
     * @throws ClassNotFoundException
     * @throws IllegalAccessException
     * @throws InstantiationException
     */
    private void initServlet(HashMap<String, String> servletinfos, HashMap<String, String> servletmappings,
            ConcurrentHashMap<String, Servlet> servletobj)
            throws InstantiationException, IllegalAccessException, ClassNotFoundException {
        for (String servletName : servletinfos.keySet()) {
            Servlet servlet = (Servlet) Class.forName(servletinfos.get(servletName)).newInstance();
            servletobj.put(servletName, servlet);
        }
    }

    @Override
    public ServletContext parse() {
        return null;
    }

}